package com.imooc.demo.service.impl;

import com.imooc.demo.converter.OrderMaster2OrderDTOConverter;
import com.imooc.demo.dataobject.OrderDetail;
import com.imooc.demo.dataobject.OrderMaster;
import com.imooc.demo.dataobject.ProductInfo;
import com.imooc.demo.dto.CartDTO;
import com.imooc.demo.dto.OrderDTO;
import com.imooc.demo.enums.OrderStatusEnum;
import com.imooc.demo.enums.PayStatusEnum;
import com.imooc.demo.enums.ResultEnum;
import com.imooc.demo.exception.SellException;
import com.imooc.demo.repository.OrderDetailRepository;
import com.imooc.demo.repository.OrderMasterRepository;
import com.imooc.demo.service.OrderService;
import com.imooc.demo.service.ProductService;
import com.imooc.demo.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Auther: 杨通通
 * @Date: 2021/11/5 22:25
 * @Description:
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        BigDecimal orderAmount = BigDecimal.valueOf(0);
        String orderId = KeyUtil.genUniqueKey();
//        1.查询商品（数量 价格）
            for(OrderDetail orderDetail:orderDTO.getOrderDetailList()){
                ProductInfo productInfo = productService.findById(orderDetail.getProductId());
                if(productInfo == null){
                    throw new SellException(ResultEnum.PRODUCT_NOT_EXISTS);
                }
                //        2.计算订单总价
                orderAmount = productInfo.getProductPrice().multiply(BigDecimal.valueOf(orderDetail.getProductQuantity()))
                        .add(orderAmount);

                BeanUtils.copyProperties(productInfo,orderDetail);

                orderDetail.setOrderId(orderId);
                orderDetailRepository.save(orderDetail);

            }



//        3.写入订单数据库

        OrderMaster orderMaster = new OrderMaster();orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMasterRepository.save(orderMaster);


//        4.扣库存
        List<CartDTO> cartList = orderDTO.getOrderDetailList().stream().map((e) ->
                new CartDTO(e.getProductId(), e.getProductQuantity())
        ).collect(Collectors.toList());
        productService.decreaseStock(cartList);

        return orderDTO;
    }

    @Override
    public OrderDTO findById(String id) {

        OrderMaster orderMaster = orderMasterRepository.findById(id).get();
        if(orderMaster == null){
            throw  new SellException(ResultEnum.ORDER_NOT_EXISTS);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);

        List<OrderDetail> details = orderDetailRepository.findByOrderId(id);
        if(CollectionUtils.isEmpty(details)){
            throw  new SellException(ResultEnum.ORDERDETAIL_NOT_EXISTS);
        }
        orderDTO.setOrderDetailList(details);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String openid, Pageable pageable) {
        Page<OrderMaster> pageOrderMaster = orderMasterRepository.findByBuyerOpenid(openid, pageable);
        List<OrderDTO> orderDtoList = OrderMaster2OrderDTOConverter.convert(pageOrderMaster.getContent());
        PageImpl<OrderDTO> orderDTOS = new PageImpl<OrderDTO>(orderDtoList);
        return orderDTOS;
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderMaster orderMaster = orderMasterRepository.findById(orderDTO.getOrderId()).get();
        if(orderMaster == null){
            throw new SellException(ResultEnum.ORDER_NOT_EXISTS);
        }
//        判断订单状态
            if(!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
                throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
            }
//        修改订单状态
            orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        OrderMaster saveResult = orderMasterRepository.save(orderMaster);
        if(saveResult == null){
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
//        返还库存

        List<OrderDetail> detailList = orderDetailRepository.findByOrderId(orderDTO.getOrderId());
        if(CollectionUtils.isEmpty(detailList)){
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXISTS);
        }

       List<CartDTO> details = detailList.stream().map((e)->
                new CartDTO(e.getProductId(),e.getProductQuantity())
                ).collect(Collectors.toList());
        productService.increaseStock(details);

//        如果已支付退款
        if(orderMaster.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())){
            //todo 退款操作
        }
        BeanUtils.copyProperties(orderMaster,orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {

        OrderMaster orderMaster = orderMasterRepository.findById(orderDTO.getOrderId()).get();
        if(!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        orderMaster.setOrderStatus(OrderStatusEnum.FINISH.getCode());
        OrderMaster result = orderMasterRepository.save(orderMaster);
        BeanUtils.copyProperties(result,orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        OrderMaster orderMaster = orderMasterRepository.findById(orderDTO.getOrderId()).get();
        if(!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        if(!orderMaster.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }


        orderMaster.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster result = orderMasterRepository.save(orderMaster);
        BeanUtils.copyProperties(result,orderDTO);
        return orderDTO;
    }
}